<template>
    <div class="upload-container">
        <el-button icon='upload' class="upload-image-btn" :style="{background:color,borderColor:color}" @click=" dialogVisible=true" type="primary">上传图片
        </el-button>
        <el-dialog v-model="dialogVisible">
            <template>
              <el-upload
                  class="editor-slide-upload"
                  :class="[{'show-picture-card': disabled }]"
                  :action="UPLOADER_URL"
                  :multiple="false"
                  :file-list="fileList"
                  :show-file-list="true"
                  list-type="picture-card"
                  :on-remove="handleRemove"
                  :on-success="handleSuccess"
                  :before-upload="beforeUpload"
                  :accept="accept"
                  :on-change="handleChange"
                  >
                  <el-button size="small" type="primary">点击上传</el-button>
                  <div slot="tip" class="el-upload__tip">最多上传10张图片</div>
              </el-upload>
            </template>
            <el-button @click="handCancelSubmit">取 消</el-button>
            <el-button type="primary" @click="handleSubmit">确 定</el-button>
        </el-dialog>
    </div>
</template>
<script>
// 文件上传测试地址 http://123.206.189.55:28810/cos/upload
// 文件上传的正式服地址http://dfs.upload1.jzexueyun.com
const IMAGE_MAXSIZE = 5;
export default {
    name: 'editorSlideUpload',
    props: {
        color: {
            type: String,
            default: '#20a0ff'
        }
    },
    data() {
        return {
            dialogVisible: false,
            listObj: {},
            fileList: [],
            UPLOADER_URL: process.env.UPLOAD_URL,
            accept: '.jpg,.gif,.png,.jpeg'
        }
    },
    mounted() {
        console.log(this.UPLOADER_URL);
    },
    computed: {
        disabled() {
            return this.fileList.length < 10 ? false : true;
        }
    },
    methods: {
        checkAllSuccess() {
            return Object.keys(this.listObj).every(item => this.listObj[item].hasSuccess)
        },
        handleSubmit() {
            const arr = Object.keys(this.listObj).map(v => this.listObj[v])
      // console.log(this.listObj , 'ahjdaskdjkasjdkajs');
            if (!this.checkAllSuccess()) {
                this.$message('请等待所有图片上传成功 或 出现了网络问题，请刷新页面重新上传！')
                return
            }    
            this.$emit('successCBK', arr.splice(-10));
            this.listObj = {}
            this.fileList = []
            this.dialogVisible = false
        },
        handCancelSubmit() {
            this.dialogVisible = false;
        },
        handleSuccess(response, file) {
            const uid = file.uid
            const objKeyArr = Object.keys(this.listObj);
            console.log(this.listObj, 'this.listObj')
            for (let i = 0, len = objKeyArr.length; i < len; i++) {
                if (this.listObj[objKeyArr[i]].uid === uid) {
                    this.listObj[objKeyArr[i]].url = response.content.accessUrl;
                    this.listObj[objKeyArr[i]].hasSuccess = true
                    return
                }
            }
      
        },
        handleRemove(file) {
      // console.log(file, "这是一个remove");
            if (file) {
                const uid = file.uid
                const objKeyArr = Object.keys(this.listObj)
                for (let i = 0, len = objKeyArr.length; i < len; i++) {
                    if (this.listObj[objKeyArr[i]].uid === uid) {
                        delete this.listObj[objKeyArr[i]]
                        this.fileList.splice(i, 1);
                        return
                    }
                }
            }
        },
        beforeUpload(file) {
            if (file.size === 0) {
                this.$message({
                    type: 'error',
                    message: '上传文件大小必须大于0KB'
                })
                this.fileList.splice(-1);  
                return false;
            }
        
            if ((file.size / 1048576).toFixed(2) > IMAGE_MAXSIZE) {
                this.$message({
                    type: 'error',
                    message: `上传文件大小大于${IMAGE_MAXSIZE}M`
                });

                this.fileList.splice(-1);
            // this.fileList[this.fileList.length] = temp;
                return false;
            }
            const isJPG = (file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg' ||file.type === 'image/gif');
            if (!isJPG) {
                this.$message.error('上传图片仅支持jpg、gif、jpeg、png格式!');
                this.fileList.splice(-1);
                return false;
            }

            const _self = this
            const _URL = window.URL || window.webkitURL
            const fileName = file.uid
            this.listObj[fileName] = {}
      
            return new Promise((resolve, reject) => {
                const img = new Image()
                img.src = _URL.createObjectURL(file)
                img.onload = function() {
                    _self.listObj[fileName] = { hasSuccess: false, uid: file.uid, width: this.width, height: this.height }
                }
                resolve(true)
            })
        },
        handleChange(file, fileList) {
            this.fileList = fileList.slice(-10);
        }
    }
}
</script>

<style rel="stylesheet/scss" lang="scss">
    .upload-container {
        .editor-slide-upload {
            margin-bottom: 20px;
        }
    }
    .el-upload__tip {
      text-align: center;
      font-size: 14px;
    }
    .show-picture-card {
      .el-upload--picture-card {
        display: none;
      }
    }
</style>
